import { toSuccess, useEntityManager } from "@sker/core"
import { AutoFile } from "@sker/entities"
import { useData } from "@sker/runtime"
import { In } from "typeorm"
import { z } from "zod"


export default async () => {
    const input = z.object({
        version: z.number(),
        list: z.array(z.object({
            path: z.string(),
            content: z.string()
        }))
    })
    const body = input.parse(useData())

    await useEntityManager(async m => {
        const list = body.list.map(item => {
            return m.create(AutoFile, {
                path: item.path,
                content: item.content,
                version: body.version,
                md5: ``
            })
        })
        const paths = list.map(it => it.path)
        const exisitFiles = await m.find(AutoFile, { where: { version: body.version, path: In(paths) } })
        const toSaveFiles = list.map(it => {
            const item = exisitFiles.find(e => e.path === it.path)
            if (item) {
                it.id = item.id;
                return it;
            }
            return it;
        })
        await m.save(AutoFile, toSaveFiles)
    })
    return toSuccess(true)
}